<template>
    <van-pull-refresh v-model="isLoading" success-text="刷新成功" @refresh="OnRefresh">
        <van-list v-model:loading="loading" :offset="10" :finished="finished" finished-text="没有更多了" @load="OnLoad">

            <van-search v-model="search" shape="round" background="#000000" placeholder="请输入搜索关键词" @search="onSearch" />
            <div class="game-item" v-for="(item, index) in list" @click="Info(item.id)">
                <div class="game-item-img">
                    <img :src="item.avatar_text" alt="">
                </div>
                <div class="game-item-info">
                    <p>{{ item.gamename }}</p>
                    <p>{{ item.sizi }}MB &nbsp;|&nbsp; {{ item.adapt }}</p>
                    <button type="button" @click.stop="download(item.id)">下载</button>
                </div>
            </div>

        </van-list>
    </van-pull-refresh>

    <Tabbar />
</template>

<script setup>
import { ref } from 'vue';

const { proxy } = getCurrentInstance();
const business = ref(proxy.$business.value)

const page = ref(1);
const list = ref([]);
const search = ref('');

const finished = ref(false);//上拉加载是否完成
const isLoading = ref(false);//下拉刷新开关
const loading = ref(false);//上拉加载开关


// 下拉刷新
const OnRefresh = () => {
    isLoading.value = true;
    loading.value = true;
    finished.value = false;
    list.value = [];
    page.value = 1;

    setTimeout(OnLoad, 1500)
};

// 上拉加载
const OnLoad = async () => {
    if (finished.value === true) isLoading.value = false;
    const params = {
        page: page.value,
        search: search.value
    }

    const res = await proxy.$http.post({
        url: '/games/getgameslist',// 接口地址
        params
    })

    loading.value = false;
    isLoading.value = false;
    // finished.value = true;

    if (res.code === 1) {
        let count = res.data.count;
        list.value = list.value.concat(res.data.item);

        if (list.value.length >= count) {
            finished.value = true;

            return false;
        }

        page.value += 1;
    } else {
        finished.value = true;
    }
}

// 搜索
const onSearch = () => {
    OnRefresh();
}

//监听，搜索值变化时，触发搜索
watch(search, (newVal, oldVal) => {
    if (newVal !== oldVal) {
        list.value = [];
        page.value = 1;
        OnLoad();
    }
})

// 跳转到详情页
const Info = (id) => {
    proxy.$router.push({
        path: '/game/info',
        query: {
            id
        }
    })

}

// 下载
const download = async (id) => {
    if (!business.value.id) {
        proxy.$fail('请先登录')
        setTimeout(() => {
            proxy.$router.push('/login')
        }, 1000)
    }
    // 判断用户的会员时间是不是大于现在的时间（秒级）
    if (business.value.vipendtime < Date.now() / 1000) {
        proxy.$fail('暂无下载权限，请先成为会员')
        setTimeout(() => {
            proxy.$router.push('/vip')
        }, 1000)
    }

    // // 动态创建表单提交（解决Ajax无法触发下载的问题）
    // const form = document.createElement('form');
    // form.method = 'post';
    // form.action = '/games/games/download'; // 后端下载接口地址

    // // 添加游戏ID参数
    // const inputId = document.createElement('input');
    // inputId.type = 'hidden';
    // inputId.name = 'id'; // 与后端接收的参数名一致
    // inputId.value = id;
    // form.appendChild(inputId);

    // // 添加用户ID参数（注意后端接收的是busid）
    // const inputBusId = document.createElement('input');
    // inputBusId.type = 'hidden';
    // inputBusId.name = 'busid'; // 与后端参数名保持一致
    // inputBusId.value = business.value.id;
    // form.appendChild(inputBusId);

    // // 添加用户账号
    // const inputBusName = document.createElement('input');
    // inputBusName.type = 'hidden';
    // inputBusName.name = 'usernumber'; // 与后端参数名保持一致
    // inputBusName.value = business.value.usernumber;
    // form.appendChild(inputBusName);


    // // 提交表单并清理
    // document.body.appendChild(form);
    // form.submit();
    // document.body.removeChild(form);

    // 不采用表单提交，直接ajax post 提交
    const params = {
        id,
        busid: business.value.id,
        usernumber: business.value.usernumber
    }

    const res = await proxy.$http.post({
        url: '/games/download',// 接口地址
        params
    })

    if (res.code === 1) {
        const address = "https://www.schoolwallback.zhouzhihua.cn/uploads/" + res.data.arr[1] + "/" + res.data.arr[2];
        // 创建一个a标签，设置下载链接和文件名
        console.log(address);

        const link = document.createElement('a');
        link.href = address;
        link.download = res.data.names;
        // 将a标签添加到文档中并模拟点击
        document.body.appendChild(link);
        link.click();
        // 下载完成后移除a标签
        document.body.removeChild(link);
        setTimeout(() => {
            proxy.$toast('加入下载列表')
        }, 100)
    } else {
        proxy.$fail(res.msg)
    }
}
</script>

<style scoped>
.game-item {
    display: flex;
    padding: 15px;
}

.game-item-img {
    width: 70px;
    height: 70px;
    border-radius: 20%;
}

.game-item-img img {
    width: 100%;
    height: 100%;
    border-radius: 20%;
    object-fit: cover;
}

.game-item-info {
    flex: 1;
    margin-left: 15px;
    /* 相对定位 */
    position: relative;
}

.game-item-info :nth-child(2) {
    opacity: 0.5;
    font-size: 14px;

}

/* 鼠标移上去按钮变化 */
.game-item-info button:hover {
    background-color: green;
    color: #000000;
}

/* 点击的时候再变化 */
.game-item-info button:active {
    background-color: #000000;
    color: green;
}

.game-item-info button {
    /* 绝对定位 */
    position: absolute;
    right: 0px;
    top: 50%;
    transform: translateY(-50%) translateX(-20%);
    background-color: #000000;
    border: 1.5px solid green;
    padding: 5px 15px;
    /* 字间距 */
    letter-spacing: 5px;
    /* 椭圆，左右圆 */
    border-radius: 20px;
    color: green;
}
</style>
